(function(){
function Process(){
    var breadcrumb = new Breadcurmb({
        prefix: [
            {text: '状态管理', anchor: '/status'}
        ],
        curr: '进程列表'
    });

    var ProcInfoModel = Backbone.Model.extend({
        defaults: {
            minionId: '',
            name: '',
            user: '',
            ports: '',
            path: '',
            startCmd: '',
            psStr: '',
            remark: '',
            autoRestart: true,
        },
        url: '/process/config',
        validate: function(attrs, options){

        },
        create: function(){
            console.log()
            var self = this;
            $.ajax({
                type: 'POST',
                url: this.url + '/create',
                data: self.toJSON(),
                success: function(result){
                    console.log(result);
                }
            });
        }, 
    });

    var RegisterView = Backbone.View.extend({
        el: '#register-menu',
        template:  _.template($("#tpl-register-form").html()),        
        events: {
            'click .btn-confirm': 'submit',
            'click .btn-reset': 'clear',
            'hidden.bs.modal': 'postHide'
        },
        map: {
            name:       '#proc-name',
            user:       '#proc-user',
            psStr:      '#proc-psstr',
            ports:      '#proc-ports',
            path:       '#proc-path',
            startCmd:   '#proc-startcmd',
            remark:     '#proc-remark',
        },
        initialize: function(options){
            this.eventBus = options.eventBus;
            this.watch();
        },
        watch: function(){
            /*
             * 注册框弹出事件暂时不通过事件总线完成
             * 考虑到弹出操作总是在render之后, 所以没有必要通过事件机制触发
             */ 
            // this.eventBus.on('show', this.show, this);
        },
        submit: function(){
            var opts = {
                minionId: app.xbox.minionId
            };
            for(var i in this.map){
                opts[i] = this.$el.find(this.map[i]).val();
            }
            console.log(opts);
            var procInfo = new ProcInfoModel(opts);
            console.log(procInfo);
            procInfo.create();
        },
        clear: function(){},
        show: function(){
            this.$el.modal('show');
        },
        postHide: function(){
            /*
             * 注册窗隐藏后, 重写url以保证当前页面状态
             */
            var url = [
                '#process/',        // 尾部的斜线要不要去掉?
                app.xbox.minionId,
            ].join('');
            appRouter.navigate(url, {trigger: true});
            this.clear();
        },
        render: function(model){
            this.model = model;
            this.$el.find('.modal-body').html(this.template(this.model.toJSON()));
            this.show();
        }
    });

    var ProcRunningView = Backbone.View.extend({
        el: '#running .process-list',
        cols: [
            {field: 'pid', title: '进程号'},
            {field: 'key', title: '关键字'},
            {field: 'psStr', title: 'ps cmd'},
            {field: 'user', title: '启动用户'},
            {field: 'startDate', title: '启动日期'},
            {field: 'port', title: '端口'},
            {
                field: 'operation', 
                title: '操作',
                /*
                 * 放弃使用bt本身的事件监听, 因为this对象无法传递
                 * events: {},
                 */
                formatter: function(value, row, index){
                    return [
                        '<span class="label label-default btn-register">注册</span>',
                        '<span class="label label-default btn-mark">标记</span>',
                    ].join('');
                }
            },
        ],
        opts:  {
            toolbar: '#running .toolbar',
        }, 
        events: {
            'click .btn-register': 'register',
            'click .btn-mark': 'mark',
        },
        initialize: function(opts){
            this.eventBus = opts.eventBus;
            this.cols = $baseCols.concat(this.cols);
            Object.assign(this.opts, $baseOpts);
            Object.assign(this.opts, {columns: this.cols});
            this.$el.bootstrapTable(this.opts);
        },
        render: function(data){
            this.$el.bootstrapTable('load', data);        
        },
        getProcInfo: function(idx){
            var data = this.$el.bootstrapTable('getData')[idx];
            var procInfo = new ProcInfoModel({
                minionId: '',
                name: data.key,
                user: data.user,
                psStr: data.psStr,
                ports: data.port,
                path: '',
                startCmd: '',
                remark: '',
            });
            return procInfo;
        },
        register: function(event){
            var idx = $(event.target).parents('tr').attr('data-index');
            var url = [
                '#process/',
                app.xbox.minionId,
                '/running/',
                idx
            ].join('');
            appRouter.navigate(url, {trigger: true});
            this.eventBus.trigger('renderRegisterView');
        },
        mark: function(event){
            var idx = $(event.target).parents('tr').attr('data-index');
            var data = this.$el.bootstrapTable('getData')[idx];
            $.ajax({
                type: 'POST',
                url: apiList.sysproc.mark,
                data: {
                    psStr: data['psStr']
                },
                success: function(result){
                    console.log(result);
                }
            });
        }
    });

    var ProcConfigView = Backbone.View.extend({
        el: '#registered .process-list',
        cols: [
            {field: 'name', title: '名称'},
            {field: 'path', title: '路径'},
            {field: 'psStr', title: 'ps cmd'},
            {field: 'owner', title: '属主'},
            {field: 'user', title: '启动用户'},
            {field: 'pids', title: '进程号'},
            {field: 'ports', title: '注册端口'},
            {field: 'portsInUse', title: '占用端口'},
            {field: 'startDate', title: '启动日期'},
            {field: 'status', title: '运行状态'},
            {field: 'remark', title: '备注'},
            {
                field: 'operation', 
                title: '操作',
                formatter: function(value, row, index){
                    return [
                        '<span class="label label-default btn-edit">编辑</span>',
                        '<span class="label label-default btn-delete">删除</span>',
                    ].join('');
                }
            },
        ],
        opts:  {
            sidePagination: 'client',
            toolbar: '#registered .toolbar',
        }, 
        initialize: function(opts){
            this.eventBus = opts.eventBus;
            this.cols = $baseCols.concat(this.cols);
            Object.assign(this.opts, $baseOpts);
            Object.assign(this.opts, {columns: this.cols});
            this.$el.bootstrapTable(this.opts);
        },
        render: function(data){
            this.$el.bootstrapTable('load', data);        
        },
    });

    var CntView = Backbone.View.extend({
        // el与initialize一样是bk的关键字, 不能重命名为其它
        el: '#page-cnt',
        template:  _.template($("#tpl-process").html()),
        initialize: function() {
            // backbone的事件总线机制, 子视图之间可以由总线上报到主视图再与其他子视图通信
            this.eventBus = _.extend({}, Backbone.Events);
            this.eventBus.on('renderRegisterView', this.renderRegisterView, this);            
            // 注意: 模板的渲染要放在表格初始化之前
            this.$el.html(this.template());

            this.breadcrumbView = new BreadcrumbView({model: breadcrumb});
            this.procRunningView = new ProcRunningView({
                eventBus: this.eventBus,
                model: this.model
            });
            this.registerView = new RegisterView({
                eventBus: this.eventBus,
                model: this.model
            });
            this.procConfigView = new ProcConfigView({
                eventBus: this.eventBus,
                model: this.model
            });
            this.fetchProcs();
        },
        render: function(data){
            // 进程列表渲染
            this.procRunningView.render(data.rows);
            this.procConfigView.render(data.procInCfgs);
            this.renderRegisterView();
        },
        renderRegisterView: function(){
            // 注册框状态, 只有当procType, idx两个参数同时存在时才可以生效
            if(!(app.xbox.procType && app.xbox.idx)) return;

            // procInfo变量应该是一个model对象
            if(app.xbox.procType == 'running'){
                var procInfo = this.procRunningView.getProcInfo(app.xbox.idx);
            }else if(app.xbox.procType == 'register'){
                // var procInfo = this.ProcConfigView.getProcInfo(app.xbox.idx);
            }
            this.registerView.render(procInfo);
        },
        fetchProcs: function(){
            var self = this;
            $.ajax({
                type: 'GET',
                url: apiList.process.query,
                data: {
                    minionId: app.xbox.minionId
                },
                success: function(result){
                    console.log(result);
                    self.render(result);
                }
            });
        },
    });
    
    var cntView = new CntView();
    console.log('process start');
    
};

app.modules.Process = Process;

})();